import 'dart:math' as math;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/country_entity.dart';
import '../../../utils/colors.dart';
import '../../../data/user_profile_entity.dart';
import '../controllers/workbench_controller.dart';
import '../models/workbench_models.dart';

class WorkbenchView extends GetView<WorkbenchController> {
  const WorkbenchView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() {
        final data = controller.workbenchData.value;
        if (data == null) {
          return const Center(child: Text('暂无数据'));
        }

        return _buildWorkbenchContent(data);
      }),
    );
  }

  /// 构建工作台内容
  Widget _buildWorkbenchContent(WorkbenchModel data) {
    return Stack(
      children: [
        Image.asset('assets/images/work/work_bg.jpg', width: Get.width, fit: BoxFit.fill,),
        Image.asset('assets/images/work/work_page_bg.png', width: Get.width, fit: BoxFit.fitWidth,),
        SafeArea(
          child: SingleChildScrollView(
            child: Column(
              children: [
                // 公司信息卡片
                _buildCompanyInfoCard(data.userProfile),
                SizedBox(height: 16.h),

                // 操作卡片
                _buildActionCards(data.actionCards),
                SizedBox(height: 16.h),

                // 功能列表
                _buildFunctionSections(data.functionSections),
                SizedBox(height: 20.h),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建公司信息卡片
  Widget _buildCompanyInfoCard(UserProfileEntity userProfile) {
    return Container(
      // margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(16.w),
      child: Row(
        children: [
          // 头像和国家标识
          Stack(
            children: [
              Transform.translate(
                offset: Offset(0, -5),
                child: Transform.rotate(
                  angle: -math.pi / 12,
                  child: Container(
                    width: 50.w,
                    height: 50.w,
                    decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      border: Border.all(color: Colors.white, width: 2),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: CachedNetworkImage(imageUrl:userProfile.avatar, fit: BoxFit.cover),
                    ),
                  ),
                ),
              ),
              Positioned(
                left: 3,
                  right: 3,
                  bottom: 0,
                  child: Container(
                      decoration: BoxDecoration(
                        shape: BoxShape.rectangle,
                        border: Border.all(color: Colors.white, width: 1),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: ClipRRect(
                          borderRadius: BorderRadius.circular(4),
                          child: Image.asset(CountryEntity.getCountryImage2(userProfile.country)))),
              ),
            ],
          ),
          SizedBox(width: 10.w),

          // 公司信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  userProfile.nickName.isNotEmpty
                      ? userProfile.nickName
                      : '百达利进出口有限公司',
                  style: TextStyle(
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    color: AppColors.color_333333,
                  ),
                ),
                SizedBox(height: 5.h),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 15.w,
                    vertical: 5.h,
                  ),
                  decoration: BoxDecoration(
                    image: DecorationImage(image: AssetImage('assets/images/work/work_identity_bg.png')),
                    borderRadius: BorderRadius.circular(12.r),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Image.asset(userProfile.vipEntity.levelAssets, width: 15,),
                      SizedBox(width: 4.w),
                      Text(
                        userProfile.getIdentity().name,
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: AppColors.color_FF6B35,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),

          // 右侧操作按钮
          Column(
            children: [
              Text('操作1', style: TextStyle(fontSize: 10),),
              SizedBox(height: 5.h),
              Text('操作1', style: TextStyle(fontSize: 10),),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建操作卡片
  Widget _buildActionCards(List<ActionCard> actionCards) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        spacing: 8,
        children: actionCards.map((card) {
          return Expanded(
            child: _buildActionCard(card),
          );
        }).toList(),
      ),
    );
  }

  /// 构建单个操作卡片
  Widget _buildActionCard(ActionCard card) {
    final color = Color(int.parse(card.color.replaceFirst('#', '0xFF')));
    return InkWell(
      onTap: () => controller.onActionCardTap(card),
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(image: AssetImage(card.backgroud), fit: BoxFit.cover),
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Stack(
          alignment: AlignmentDirectional.centerStart,
          children: [
            Container(
              width: 4.w,
              height: 30.h,
              decoration: BoxDecoration(
                color: color,
                borderRadius: BorderRadius.circular(2.r),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                children: [
                  Expanded(
                    child: Text(
                      card.title,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                        color: AppColors.color_333333,
                      ),
                    ),
                  ),
                  Image.asset(card.icon, width: 24.w, height: 24.w),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建功能分区
  Widget _buildFunctionSections(List<FunctionSection> sections) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      decoration: BoxDecoration(
        color: Color(0x80EAF7FF),
        borderRadius: BorderRadius.circular(12.r),

      ),
      child: Column(
        children: sections.map((section) {
          return _buildFunctionSection(section);
        }).toList(),
      ),
    );
  }

  /// 构建单个功能分区
  Widget _buildFunctionSection(FunctionSection section) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (section.title.isNotEmpty) ...[
          Padding(
            padding: EdgeInsets.only(top: 16, left: 16, right: 16),
            child: Text(
              section.title,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.w600,
                color: AppColors.color_333333,
              ),
            ),
          ),
        ],
        if (section.items.isNotEmpty) _buildFunctionItems(section.items),
      ],
    );
  }

  /// 构建功能项网格
  Widget _buildFunctionItems(List<FunctionItem> items) {
    return Padding(
      padding: EdgeInsets.all(16.w),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          crossAxisSpacing: 16.w,
          mainAxisSpacing: 16.h,
          childAspectRatio: 0.8,
        ),
        itemCount: items.length,
        itemBuilder: (context, index) {
          return _buildFunctionItem(items[index]);
        },
      ),
    );
  }

  /// 构建单个功能项
  Widget _buildFunctionItem(FunctionItem item) {
    return GestureDetector(
      onTap: () => controller.onFunctionItemTap(item),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Stack(
            children: [
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Center(
                  child: Image.asset(item.icon, width: 35.w, height: 35.w),
                ),
              ),
              if (item.unreadCount > 0)
                Positioned(
                  right: 0,
                  top: 0,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 6.w,
                      vertical: 2.h,
                    ),
                    decoration: BoxDecoration(
                      color: AppColors.color_F44336,
                      borderRadius: BorderRadius.circular(10.r),
                    ),
                    constraints: BoxConstraints(
                      minWidth: 16.w,
                      minHeight: 16.w,
                    ),
                    child: Text(
                      item.unreadCount > 99
                          ? '99+'
                          : item.unreadCount.toString(),
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 10.sp,
                        fontWeight: FontWeight.w500,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ),
            ],
          ),
          SizedBox(height: 8.h),
          Text(
            item.title,
            style: TextStyle(
              fontSize: 12.sp,
              color: AppColors.color_333333,
              fontWeight: FontWeight.w500,
            ),
            textAlign: TextAlign.center,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }
}
